package com.inspire.springboot.test.ttl;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.alibaba.ttl.threadpool.TtlExecutors;

import java.util.concurrent.*;

/*
第一次种方式使用TTL:
配置TTL依赖方式
 */
public class TransmittableThreadLocalDemo {

    private static TimeUnit keepAliveTimeUnit = TimeUnit.MINUTES;

    private static ExecutorService tomcatExecutors = new ThreadPoolExecutor(8, 16,
            60L, keepAliveTimeUnit, new LinkedBlockingDeque<>(100));

    //    private static ExecutorService controlExecutors = new ThreadPoolExecutor(8, 16,
//            60L, keepAliveTimeUnit, new LinkedBlockingDeque<>(100));
    // 使用ttl线程池
    private static Executor controlExectutors = TtlExecutors.getTtlExecutorService(Executors.newFixedThreadPool(5));


    private static TransmittableThreadLocal<Integer> requestIdTransmittableTheadLocal = new TransmittableThreadLocal<>();


    public static void main(String[] args) {

        for (int i = 0; i < 10; i++) {
            tomcatExecutors.submit(new ControlTask(i));
        }

        tomcatExecutors.shutdown();
    }

    static class ControlTask implements Runnable {

        private int i;

        public ControlTask(int i) {
            this.i = i;
        }

        @Override
        public void run() {
            requestIdTransmittableTheadLocal.set(i);
            System.out.println(Thread.currentThread().getName() + ":" + i);
            // ttl线程池只有execute()方法
            controlExectutors.execute(new BusinessTask(Thread.currentThread().getName()));
        }
    }

    static class BusinessTask implements Runnable {
        private String parentThreadName;

        public BusinessTask(String parentThreadName) {
            this.parentThreadName = parentThreadName;
        }



        @Override
        public void run() {
            System.out.println("parentThreadName:" + parentThreadName + ",id: " + requestIdTransmittableTheadLocal.get());
        }
    }


}
